<?php

namespace app\admin\model;

use app\common\model\TimeModel;
use think\facade\Cache;

class AppIpReject extends TimeModel
{

    protected $name = "app_ip_reject";

    protected $deleteTime = "delete_time";

    public static $withAppend = ['ip_info'];

    public static function initRecord($ip)
    {
        $model = static::where('ip', $ip)->find();

        if (empty($model)) {
            $model = new static();

            $model->ip = $ip;
            $model->count = 0;
        }

        $model->count++;
        $model->save();
    }

    public function getIpInfoAttr()
    {
        $ip = $this->getAttr('ip');

        $cache_key = md5($ip);

        $info = Cache::get($cache_key);

        if (is_null($info)) {
            $info = get_ip_info($ip);

            Cache::set($cache_key, $info, 86400 * 30);
        }

        return $info;
    }
}
